package com.fy.fyspace.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fy.fyspace.common.result.Result;
import com.fy.fyspace.constant.KeysConstant;
import com.fy.fyspace.mapper.LikePictureMapper;
import com.fy.fyspace.mapper.PictureMapper;
import com.fy.fyspace.model.entity.LikePicture;
import com.fy.fyspace.model.entity.Picture;
import com.fy.fyspace.model.enums.picture.PictureDeleteStatusEnum;
import com.fy.fyspace.model.vo.user.UserSessionVO;
import com.fy.fyspace.service.LikePictureService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import static org.springframework.beans.BeanUtils.copyProperties;

/**
 * <p>
 * 图片点赞表 服务实现类
 * </p>
 *
 * @author fwq
 * @since 2025-06-26
 */
@Service
public class LikePictureServiceImpl extends ServiceImpl<LikePictureMapper, LikePicture> implements LikePictureService {

    @Resource
    private LikePictureMapper likePictureMapper;

    @Resource
    private PictureMapper pictureMapper;
    
    @Resource
    private HttpSession httpSession;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    private void updatePictureCache(Long pictureId, String field, Integer newValue) {
        int maxPage = 5; // 只遍历前5页
        int pageSize = 30; // 和你的缓存分页一致
        for (int page = 1; page <= maxPage; page++) {
            String cacheKey = "picture:data" + String.format("default:%d:%d", page, pageSize);
            String cachedData = (String) redisTemplate.opsForValue().get(cacheKey);
            if (cachedData != null && !cachedData.isEmpty()) {
                Map<String, Object> result = cn.hutool.json.JSONUtil.toBean(cachedData, Map.class);
                Object recordsObj = result.get("records");
                if (recordsObj instanceof List) {
                    List<Map<String, Object>> records = (List<Map<String, Object>>) recordsObj;
                    boolean updated = false;
                    for (Map<String, Object> pic : records) {
                        Object idObj = pic.get("id");
                        if (idObj != null && pictureId.toString().equals(idObj.toString())) {
                            if (pic.containsKey(field)) { // 只更新已存在的字段
                                pic.put(field, newValue);
                                updated = true;
                            }
                            break;
                        }
                    }
                    if (updated) {
                        result.put("records", records);
                        String newCache = cn.hutool.json.JSONUtil.toJsonStr(result);
                        redisTemplate.opsForValue().set(cacheKey, newCache, 5, java.util.concurrent.TimeUnit.MINUTES);
                    }
                }
            }
        }
    }

    @Override
    public Result batchLikePictures(String picIds) {
        UserSessionVO userSessionVO = (UserSessionVO) httpSession.getAttribute(KeysConstant.LOGIN_SESSION_KEY);
        if (StringUtils.isBlank(picIds)) {
            return Result.error("图片ID不能为空");
        }
        String[] picIdArr = picIds.split(",");
        Set<Long> picIdSet = Arrays.stream(picIdArr)
                .filter(StringUtils::isNotBlank)
                .map(Long::parseLong)
                .collect(Collectors.toSet());

        for (Long picId : picIdSet) {
            LikePicture like = likePictureMapper.selectOne(
                    new LambdaQueryWrapper<LikePicture>()
                            .eq(LikePicture::getLikeUserId, userSessionVO.getId())
                            .eq(LikePicture::getPicId, picId)
            );
            if (like == null) {
                // 没有记录，插入新点赞
                Picture picture = pictureMapper.selectById(picId);
                if (picture == null) continue;
                LikePicture newLike = new LikePicture();
                copyProperties(picture, newLike);
                Integer likeCount = picture.getLikeCount() == null ? 1 : picture.getLikeCount() + 1;
                newLike.setId(null);
                newLike.setPicId(picture.getId());
                newLike.setCreateTime(new Date());
                newLike.setUpdateTime(new Date());
                newLike.setIsDelete(PictureDeleteStatusEnum.NOT_DELETE.getValue());
                newLike.setCreateUserId(picture.getUserId());
                newLike.setLikeUserId(userSessionVO.getId());
                likePictureMapper.insert(newLike);
                picture.setLikeCount(likeCount);
                pictureMapper.updateById(picture);
                // 同步更新缓存
                updatePictureCache(picId, "likeCount", likeCount);
            } else if (like.getIsDelete() == PictureDeleteStatusEnum.IS_DELETE.getValue()) {
                Picture picture = pictureMapper.selectById(picId);
                like.setIsDelete(PictureDeleteStatusEnum.NOT_DELETE.getValue());
                like.setUpdateTime(new Date());
                Integer likeCount = picture.getLikeCount() == null ? 1 : picture.getLikeCount() + 1;
                picture.setLikeCount(likeCount);
                likePictureMapper.updateById(like);
                pictureMapper.updateById(picture);
                // 同步更新缓存
                updatePictureCache(picId, "likeCount", likeCount);
            }
            // else 已点赞，跳过
        }
        return Result.success();
    }

}
